package com.unicom.office.builder;

import com.unicom.office.config.OfficeConfig;
import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.unit.*;
import com.unicom.office.util.FileUtil;

import java.util.List;

public abstract class OfficeBuilder {
    protected OfficeConfig config;
    protected OfficeRuntime runtime;

    public OfficeBuilder(OfficeConfig config, OfficeRuntime runtime){
        this.config = config;
        this.runtime = runtime;
    }

//    public void build(OfficeUnit unit, String targetPath){
//        Object root = build2(unit, null);
//        writeFile(root, targetPath);
//    }

    public void build(List<OfficeUnit> units, String targetPath){
        if(units == null || units.size() == 0){
            return;
        }else if(units.size() == 1) {
            RootUnit rootUnit = (RootUnit) units.get(0);
            build(rootUnit, targetPath);
        }else{
            for (Integer i = 0; i < units.size(); i++) {
                RootUnit rootUnit = (RootUnit) units.get(i);
                String path = FileUtil.addSuffix(targetPath, i.toString());
                build(rootUnit, path);
            }
        }
    }

    public void build(RootUnit rootUnit, String targetPath){
        if(rootUnit.getFilePath() != null && rootUnit.getFilePath().trim().length() > 0){
            targetPath = rootUnit.getFilePath();
        }
        Object root = build2(rootUnit, null);
        writeFile(root, targetPath);
    }

    public void setConfig(OfficeConfig config) {
        this.config = config;
    }

    public void setRuntime(OfficeRuntime runtime) {
        this.runtime = runtime;
    }

    public abstract Object build2(OfficeUnit unit, Object parent);
    protected abstract Object buildRow(RowUnit unit, Object parent);
    protected abstract Object buildCell(CellUnit unit, Object parent);
    protected abstract Object buildParagraph(ParagraphUnit unit, Object parent);
    protected abstract Object buildTextbox(TextboxUnit unit, Object parent);
    protected abstract Object buildTextrange(TextRangeUnit unit, Object parent);
    protected abstract Object buildPicture(PictureUnit unit, Object parent);
    public abstract void writeFile(Object result, String targetPath);
}
